package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 记录业务增、删、改的操作的切面类
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    @Around("@annotation(com.itheima.anno.Log)")
    public Object around(ProceedingJoinPoint pjp) {
        OperateLog operateLog = new OperateLog();

        long start = System.currentTimeMillis();
        Object result = pjp.proceed();

        //操作人
        String jwt = request.getHeader("token");
        Integer empId = (Integer) JwtUtils.parseJWT(jwt).get("id");
        operateLog.setOperateUser(empId);
        //操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        //操作类名
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        //操作方法名
        operateLog.setMethodName(pjp.getSignature().getName());
        //操作方法参数
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
        //操作方法的返回值
        operateLog.setReturnValue(result.toString());
        //操作耗时
        operateLog.setCostTime(System.currentTimeMillis() - start);

        //向operate_log表中添加数据，使用 operateLogMapper
        operateLogMapper.insert(operateLog);

        return result;
    }
}
